package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import model.Subject;
import model.SubjectMsg;
import service.SubjectService;
import service.UserService;
import service.impl.SubjectServiceImpl;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/subjectList")
public class SubjectListServlet extends HttpServlet {

    SubjectService subjectService=new SubjectServiceImpl();
    UserService userService=new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
   //将前端的参数转为json
        BufferedReader reader = new BufferedReader(request.getReader());
        StringBuilder json = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            json.append(line);
        }
        JSONObject jsonObject = JSON.parseObject(json.toString());
        int pageSize = 8 ;
        //解析前端的参数：pageIndex，pageSize暂指定为5
        int pageIndex = Integer.parseInt(jsonObject.getString("pageIndex"));
        //创建raceMsgList容器
        List<SubjectMsg> subjectMsgList =new ArrayList<>();

        List<Subject> subjects = subjectService.findByPage(pageIndex,pageSize);


        for (Subject subject: subjects) {
            SubjectMsg subjectMsg=new SubjectMsg();
            //填充数据
            subjectMsg.setSubject(subject);
            subjectMsg.setUser(userService.findById(subject.getUid()));
            subjectMsgList.add(subjectMsg);
        }
        int count=subjectService.count();

        //将数据List打包为json发给前端
        JSONObject message = new JSONObject();
        message.put("subjectMsg",subjectMsgList);
        message.put("pageCount", count % pageSize != 0 ? count / pageSize + 1 : count / pageSize);
        response.getWriter().write(message.toString());

    }
}